import * as module from "@/tools/util";
import * as Request from '@/api/liubike';
import store from "@/tools/factory"
import { config, isDev, defaultAreaId } from '@/api/config';

import wx  from '@/tools/wx'
import commonJs from '@/views/commonJs/common'
import md5 from 'js-md5'

let that
let loginInfo = null;

/**
 * 转化:   that.data -> that._data
 * ev.detail -> ev.target
 * options -> this.$route.query
 */

export default {
    mixins: [commonJs],
    data() {
        return {
            free: true,
            deposit: 299,
            hasCreditFree: false,
            status: 0,
            remainder: 0, // 余额
            rechargeLists: [], // 充值金额选择列表
            selectId: 0, // 默认选择充值项
            btnStatus: 0, // 按钮选择状态
            depositCardRemains: 0,
            hasDepositCard: false,
            depositTipShow: false,
            hasDepositBenefit: false,
            depositCardArea: null,
            depositBenefitArea: "",
            canRefundBalance: false,
            myDeposit: 0,
            balance: 0,
            refundText: {},
            refundBalanceCode: "",
            refundBalanceMsg: "",
            refundDialog: false,
            errorButtonArea: false,
            errorTitle: "",
            errorContent: "",
            depositStatus: "",
            returnmoney: "", //领养赠送
            freezeMoney: "", //冻结
            givebalance: "", //赠送
            cash: "", //剩余本金
            credit: "", //信用
            pageSource: "",
            quickPayMethodText: "",
            refundButtonText: "退余额",
            depositBenefitEndTime: "",
            item: { // 充值按钮
                content: "充值"
            }
        }
    },
    mounted() {
        that = this;
        if (this.$route.query) {
            console.log("this.$route.query", this.$route.query)
            if (this.$route.query.source) {
                that.setData({
                    pageSource: this.$route.query.source
                })
            } else {
                that.setData({
                    pageSource: ""
                })
            }
            if (this.$route.query.status == 1) {
                that.setData({
                    free: false
                })
            } else {
                that.setData({
                    free: true
                })
            }
        } else {
            that.setData({
                free: true,
                pageSource: ""
            })
        }
        if (!store.get("loginInfo")) {
            return false
        }
        that.getRemainder();
    },
    methods: {
        onLoad: function (options) {
            that = this;
            if (options) {
                console.log("options", options)
                if (options.source) {
                    that.setData({
                        pageSource: options.source
                    })
                } else {
                    that.setData({
                        pageSource: ""
                    })
                }
                if (options.status == 1) {
                    that.setData({
                        free: false
                    })
                } else {
                    that.setData({
                        free: true
                    })
                }
            } else {
                that.setData({
                    free: true,
                    pageSource: ""
                })
            }
        },
        onShow() {
            if (!store.get("loginInfo")) {
                return false
            }
            that.getRemainder();
        },
        routerGo() {
            wx.redirectTo({
                url: `/paymentSetting`
            })
        },
        getQuickPaySetting() {
            Request.getQuickPaySetting().then(res => {
                if (res.success) {
                    let req = res.data;
                    if (req) {
                        let quickPayMethodText = ""
                        if (req.quickPayMethodText.indexOf("云闪付") != -1) {
                            quickPayMethodText = "云闪付"
                        } else {
                            quickPayMethodText = req.quickPayMethodText
                        }
                        that.setData({
                            quickPayMethodText: quickPayMethodText
                        })
                    }
                }
            })
        },
        changeStatus() {
            console.log("change")
            that.setData({
                free: false
            })
        },
        GMTToStr(time) {
            let date = new Date(time)
            let Str = date.getFullYear() + '-' +
                (date.getMonth() + 1) + '-' +
                date.getDate()
            return Str
        },
        popupConfirm() {
            that.setData({
                refundDialog: false
            })
        },
        refundBalance() {
            let APPDATA = that._data;
            if (APPDATA.refundBalanceCode == 20102000) {
                store.set("refundBalance", APPDATA.cash);
                store.set("refundGiveBalance", APPDATA.givebalance);
                store.set("refundType", 1);
                wx.navigateTo({
                    url: `/refund`
                })
            } else if (APPDATA.refundBalanceCode == 20102005) {
                if (!APPDATA.refundText.refundAccount) {
                    that.getRefundIng()
                } else {
                    that.setData({
                        refundDialog: true
                    })
                }
            } else if (APPDATA.refundBalanceCode == 20102010) {
                store.set("refundBalance", APPDATA.cash);
                store.set("refundGiveBalance", APPDATA.givebalance);
                store.set("refundType", 2);
                wx.navigateTo({
                    url: `/refund`
                })
            } else {
                wx.showModal({
                    title: "退余额提醒",
                    content: APPDATA.refundBalanceMsg,
                    showCancel: false,
                    confirmText: "我知道了"
                })
            }
        },
        getRefundIng() {
            let time = new Date().getTime();
            let code = `appId=mini&t=${time}&appSecret=liubike666`;
            //退余额中
            Request.getRefundBalanceFormV3({ appId: "mini", t: time, sign: (md5(code)).toLocaleUpperCase() }).then(res => {
                if (res.success) {
                    let req = res.data;
                    that.setData({
                        refundText: {
                            refundAccount: req.refundAccount,
                            giveBalance: req.giveBalance,
                            balance: req.balance,
                        },
                        refundDialog: true
                    })
                }
            }).catch(err => {
                wx.showToast({
                    title: "服务器报错",
                    icon: "none"
                })
            })
        },
        getRemainder() { // 钱包余额
            const APPDATA = that._data; // 实例数据
            const defaultSelectId = APPDATA.selectId; // 当前选择目标的id
            let areaId = store.get("childRouter").areaId || defaultAreaId;
            let time = new Date().getTime();
            let code = `appId=mini&areaid=${areaId}&t=${time}&appSecret=liubike666`;
            // console.log(code, 'code')
            wx.showLoading({
                title: "加载中..."
            })
            Request.getWalletV3({ areaid: areaId, appId: "mini", t: time, sign: (md5(code)).toLocaleUpperCase() }).then(res => {
                if (!res.success) {
                    wx.showToast({
                        icon: "none",
                        title: res.msg
                    })
                }
                const data = res.data;
                let depositTipStatus = false;
                if (data.depositStatus == "FREE") {
                    depositTipStatus = true;
                }
                // 设置钱包余额
                that.setData({
                    remainder: (data.balance + data.givebalance + data.returnmoney + data.credit).toFixed(2),
                    returnmoney: data.returnmoney ? data.returnmoney.toFixed(2) : false,
                    freezeMoney: data.freezeMoney ? data.freezeMoney.toFixed(2) : false,
                    givebalance: data.givebalance.toFixed(2),
                    cash: data.balance.toFixed(2),
                    credit: data.credit ? data.credit.toFixed(2) : false,
                    balance: data.balance + data.givebalance + data.returnmoney + data.credit,
                    depositCardRemains: data.depositCardRemains,
                    hasDepositCard: data.hasDepositCard,
                    refundButtonText: data.refundBalanceCode == 20102005 ? "退余额申请中" : "退余额",
                    depositTipShow: depositTipStatus,
                    hasDepositBenefit: data.hasDepositBenefit,
                    depositCardArea: data.depositCardArea,
                    depositBenefitArea: data.depositBenefitArea,
                    myDeposit: data.deposit,
                    canRefundBalance: data.canRefundBalance,
                    status: data.status,
                    depositStatus: data.depositStatus,
                    hasCreditFree: data.hasCreditFree,
                    refundBalanceCode: data.refundBalanceCode,
                    refundBalanceMsg: data.refundBalanceMsg,
                    refundDialog: false,
                    depositBenefitEndTime: data.depositBenefitEndTime ? data.depositBenefitEndTime : ""
                });

                wx.hideLoading();
                /** 充值金额列表
                 * 面额可选择规则
                 * 当页面载入时，系统判断用户车费余额状态,当用户车费余额小于0时,
                 * 面额条目只有比用户欠费额度大的面额条目可选中可点击,其余小面额条目不可选中置灰显示
                 */
                Request.getVirtual().then(res => {
                    const rechargeArr = [];
                    res.map((item, index) => {
                        if (item.checked) {
                            that.setData({
                                selectId: index,
                            });
                        }
                        rechargeArr.push({
                            money: item.money,
                            givemoney: item.givemoney,
                            leadApp: item.leadApp,
                            id: item.id,
                            rechargeAmount: item.money + item.givemoney
                        });
                    });

                    that.setData({
                        rechargeLists: rechargeArr, // 充值金额列表
                        noId: rechargeArr[APPDATA.selectId].id,
                        rechargeAmount: rechargeArr[APPDATA.selectId].money + rechargeArr[defaultSelectId].givemoney // 默认充值金额
                    });
                });
                //获取区域配置押金金额
                Request.getPayDeposit({
                    areaId: store.get('childRouter').areaId || defaultAreaId
                }).then(res => {
                    if (res.success) {
                        that.setData({
                            deposit: res.data
                        })
                    }
                });
                //获取快捷支付是否开启
                that.getQuickPaySetting();
            }).catch(err => {
                wx.showToast({
                    icon: "none",
                    title: "获取钱包信息失败"
                })
            });
        },
        selectRechargeNum(ev) { // 选择充值金额
            const APPDATA = that._data; // 实例数据
            const curTargetData = ev.currentTarget.dataset; // 当前点击目标
            const curId = curTargetData.id; // 当前点击目标的id
            // 选择时设置id和对应的金额
            that.setData({
                selectId: curTargetData.id,
                rechargeAmount: APPDATA.rechargeLists[curId].rechargeAmount,
                noId: APPDATA.rechargeLists[curId].id
            });
        },
        turnWxpay() {
            store.set("wxWeb", `${config.wxpayURL}?&t=${new Date().getTime()}`)
            wx.navigateTo({
                url: `/wxWeb`
            })
        },
        turnRecharge() {
            wx.navigateTo({
                url: `/rechargeDeposit`
            })
        },
        returnDepositModal() { // 显示如何退还押金modal
            if (that._data.balance < 0) {
                wx.showModal({
                    title: "无法退押金",
                    content: `当前账户余额为：${that._data.balance}，请充值后再退押金`,
                    showCancel: true,
                    confirmText: "立即充值",
                    success(res) {
                        if (res.confirm) {
                            that.setData({
                                free: false
                            })
                        }
                    }
                });
                return false
            }
            Request.isrefund().then(res => {
                if (!res.success) {
                    if (res.code == 201 || res.code == 203) {
                        store.set("refundStatus", "error")
                        wx.navigateTo({
                            url: `/refundBalance`
                        })
                    } else if (res.code == 207) {
                        wx.showModal({
                            title: "退押失败",
                            content: res.msg,
                            confirmText: "立即支付",
                            showCancel: false,
                            success() {
                                if (!config.switchParkPay) {
                                    wx.navigateTo({
                                        url: `/parkPay`
                                    });
                                    return false
                                }
                                store.set("pageSource", "ARREARS_PAY")
                                wx.navigateTo({
                                    url: `/payOrder`
                                })
                            }
                        });
                    } else {
                        wx.showModal({
                            title: "退押失败",
                            content: res.msg,
                            showCancel: false
                        });
                    }
                } else {
                    store.set("refundStatus", "normal")
                    wx.navigateTo({
                        url: `/refundBalance`
                    })
                }
            })
        },
        rechargeOpts() { // 充值按钮
            const APPDATA = that._data; // 实例数据
            const openId = store.get('openid');
            wx.showLoading({
                title: '请稍候...'
            });
            // 当前用户的openid已存在(非第一次充值操作)
            if (openId) {
                that.wxpayRecharge(openId);
                return false;
            }
            that.wxloign();
        },
        wxloign() {
            wx.login({
                success: function (res) {
                    store.set('loginCode', res.code);
                    Request.getOpenIdV3({
                        code: store.get('loginCode'),
                    }).then(res => {
                        const data = res.data.data;
                        store.set('openid', data.openid);
                        that.wxpayRecharge(data.openid);
                    }).catch(err => {
                        wx.hideLoading();
                        wx.showToast({
                            icon: "none",
                            title: "充值失败"
                        });
                    });
                },
                fail: function (res) {
                    wx.hideLoading();
                    wx.showToast({
                        icon: "none",
                        title: "充值失败"
                    });
                }
            })
        },
        wxpayRecharge(openid) { // 余额微信支付
            const APPDATA = that._data; // 实例数据
            Request.wxpayRecharge({
                rid: APPDATA.noId, // 充值列表id
                appid: config.appid, // 小程序appid
                type: 'web', // 区分小程序端和App端
                openid: openid // 用户openid
            }).then(res => {
                wx.hideLoading();
                // 调用小程序支付接口
                wx.requestPayment({
                    timeStamp: `${res.timestamp}`,
                    nonceStr: res.noncestr,
                    package: res.package,
                    signType: res.signType || 'MD5',
                    paySign: res.sign,
                    success(res) {
                        wx.showToast({
                            title: '充值成功'
                        });
                        if (APPDATA.pageSource == "payOrder") {
                            let p = getCurrentPages();
                            let prevPages = p[p.length - 2];
                            store.set("refresh", "not");
                            prevPages.setData({
                                dialogType: "waitPage"
                            })
                        }
                        setTimeout(function () {
                            wx.navigateBack({
                                delta: 1 //返回的页面数，如果 delta 大于现有页面数，则返回到首页,
                            });
                        }, 1000)
                    },
                    fail(err) {
                        wx.showToast({
                            icon: "none",
                            title: "充值失败"
                        });
                    }
                });
            })
        },
        viewAgreement() { // 查看充值协议
            wx.navigateTo({
                url: `/aboutAgreement?id=1`
            })
        },
        tel: function () {
            wx.makePhoneCall({
                phoneNumber: '4006076666',
            })
        },
        lostLogin() {
            // lostLoginModal()
            // wx.showModal({
            //     content: '登录丢失, 请重新登录后用车',
            //     confirmText: '登录',
            //     success(res) {
            //         // 清除登录信息
            //         store.remove('loginInfo');
            //         // 点 `登录` 跳转到登录页面
            //         if (res.confirm) {
            //             wx.navigateTo({
            //                 url: '/mobileLogin'
            //             });
            //         }
            //     }
            // });
        },
        onShareAppMessage: function () {
            return {
                title: '小遛共享',
                path: '/index',
            }
        }
    }
}
